package io.scnb.lesson001.demo16;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CostTImeInvocationHandler implements InvocationHandler {

    private Object target;

    public CostTImeInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long startTime = System.nanoTime();
        Object result = method.invoke(this.target, args);
        long endTime = System.nanoTime();
        System.out.println(this.target.getClass() + ".m1()方法耗时（纳秒）:" + (endTime-startTime));
        return result;
    }

    public static<T> T createProxy(Object target, Class<T> targetInterface) {
        if (!targetInterface.isInterface()) {
            throw new IllegalStateException("targetInterface必须是接口类型");
        } else if (!targetInterface.isAssignableFrom(target.getClass())) {  // 判断targetInterface是不是target的父类或父接口
            throw new IllegalStateException("target必须是targetInterface接口的实现类");
        }
        // 三个参数分别为：
        // 1. 加载代理类的类加载器（这里传入的是被代理类的类加载器）
        // 2. 被代理类实现的接口列表
        // 3. 拦截的方法
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new CostTImeInvocationHandler(target));
    }
}
